import { DataTypes, Model, Sequelize } from 'sequelize';
import { User } from './User';

/**
 * 登录日志模型接口
 */
export interface LoginLogAttributes {
  id?: number;
  user_id?: number;
  username: string;
  ip_address: string;
  user_agent?: string;
  login_result: number;
  failure_reason?: string;
  session_id?: string;
  created_at?: Date;
}

/**
 * 登录日志模型类
 */
export class LoginLog extends Model<LoginLogAttributes> implements LoginLogAttributes {
  public id!: number;
  public user_id!: number;
  public username!: string;
  public ip_address!: string;
  public user_agent!: string;
  public login_result!: number;
  public failure_reason!: string;
  public session_id!: string;
  public created_at!: Date;
}

/**
 * 初始化登录日志模型
 */
export function initLoginLogModel(sequelize: Sequelize): typeof LoginLog {
  LoginLog.init(
    {
      id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true,
        comment: '日志ID，主键自增',
      },
      user_id: {
        type: DataTypes.BIGINT,
        allowNull: true,
        comment: '用户ID，登录成功时记录',
        references: {
          model: 'users',
          key: 'id',
        },
        onDelete: 'SET NULL',
      },
      username: {
        type: DataTypes.STRING(50),
        allowNull: false,
        comment: '尝试登录的用户名',
      },
      ip_address: {
        type: DataTypes.STRING(45),
        allowNull: false,
        comment: '登录IP地址',
      },
      user_agent: {
        type: DataTypes.TEXT,
        allowNull: true,
        comment: '用户代理信息',
      },
      login_result: {
        type: DataTypes.TINYINT,
        allowNull: false,
        comment: '登录结果：1-成功，0-失败',
      },
      failure_reason: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: '失败原因：用户不存在、密码错误等',
      },
      session_id: {
        type: DataTypes.STRING(128),
        allowNull: true,
        comment: '成功登录时的会话ID',
      },
      created_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        comment: '登录尝试时间',
      },
    },
    {
      sequelize,
      tableName: 'login_logs',
      modelName: 'LoginLog',
      timestamps: false, // 只需要 created_at
      underscored: true,
      indexes: [
        {
          fields: ['user_id'],
          name: 'idx_user_id',
        },
        {
          fields: ['username'],
          name: 'idx_username',
        },
        {
          fields: ['ip_address'],
          name: 'idx_ip_address',
        },
        {
          fields: ['login_result'],
          name: 'idx_login_result',
        },
        {
          fields: ['created_at'],
          name: 'idx_created_at',
        },
      ],
      comment: '登录日志表，用于安全审计',
    }
  );

  return LoginLog;
}

/**
 * 定义登录日志关联关系
 */
export function defineLoginLogAssociations(): void {
  // 登录日志属于用户（可选，因为登录失败时user_id为空）
  LoginLog.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'user',
  });

  // 用户有多个登录日志
  User.hasMany(LoginLog, {
    foreignKey: 'user_id',
    as: 'loginLogs',
  });
}
